package cmd

import (
	"fmt"
	"nest/internal/pkgerrors"

	"golang.org/x/mod/semver"
)

// 卸载包
func (cm *CommandManager) Uninstall(packageName string, version string) error {

	if version == "" {
		// 获取已安装的最新版本
		packages, err := cm.manager.ListInstalledPackages()
		if err != nil {
			return pkgerrors.Fatal(fmt.Sprintf("%s 获取已安装包失败", packageName))
		}

		var latestVersion string
		for _, pkg := range packages {
			if pkg.Name == packageName {
				// 查找匹配的最高版本
				if latestVersion == "" || semver.Compare(pkg.Version, latestVersion) > 0 {
					latestVersion = pkg.Version
				}
			}
		}
		if latestVersion == "" {
			return pkgerrors.Info(fmt.Sprintf("%s 未安装", packageName))
		}

		version = latestVersion
	}
	res, err := cm.manager.UninstallPackage(packageName, version)
	if err != nil {
		return err
	}
	//成功卸载
	pkgerrors.PrintSuccess(res)
	return nil
}
